package com.module_live.fragment;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.herewhite.sdk.Room;
import com.herewhite.sdk.WhiteBroadView;
import com.herewhite.sdk.domain.Appliance;
import com.herewhite.sdk.domain.ImageInformationWithUrl;
import com.herewhite.sdk.domain.MemberState;
import com.herewhite.sdk.domain.Scene;
import com.lib.app.CodeUtil;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.px_dp.DisplayUtil;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.ui.fragment.BaseAppFragment;
import com.lib.utls.picture_select.PhotoUtil;
import com.lib.utls.upload.QiNiuUploadTask;
import com.lib.utls.upload.initerface.FileUploadListener;
import com.luck.picture.lib.entity.LocalMedia;
import com.module_live.R;
import com.module_live.R2;
import com.module_live.activity.DaYiConnectRoomActivity;
import com.module_live.bean.CourseUploadBean;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2020/7/16 0016.
 */

@SuppressLint("ValidFragment")
public class ChatWhiteBroadFragment extends BaseAppFragment {

    WhiteBroadView whiteBroadView;

    @BindView(R2.id.oto_f_board)
    FrameLayout f_board;

    @BindView(R2.id.oto_lin_insert)
    LinearLayout lin_insert;
    @BindView(R2.id.oto_tv_progress)
    TextView tv_progress;

    String identity;

    Room room;

    @SuppressLint("ValidFragment")
    public ChatWhiteBroadFragment(WhiteBroadView whiteBroadView, Room whiteBoardRoom) {

        this.whiteBroadView = whiteBroadView;

        this.room = whiteBoardRoom;

        showLog("WhiteBoardFragment");

    }

    @Override
    protected void onCreateView(View view, Bundle savedInstanceState) {

        identity = SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserIdentity();

        f_board.removeAllViews();
        f_board.addView(whiteBroadView);

        showLog("onCreateView" + "Width:" + f_board.getWidth() + "Height:" + f_board.getHeight());


//        setBoradTool(Appliance.PENCIL);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_room_white;
    }


    @Override
    public void onStop() {
        super.onStop();

        f_board.removeAllViews();

    }

    @Override
    public void onResume() {
        super.onResume();
        showLog("onResume" + "Width:" + f_board.getWidth() + "Height:" + f_board.getHeight());

        refreshRoom();

    }


    public void refreshRoom() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (room != null) {
                    showLog("刷新白板");
                    room.refreshViewSize();

                }
            }
        }, 1000);
    }


    public void setRoom(Room room) {

        this.room = room;

        refreshRoom();

    }


    public void setBoradTool(String pencil) {
        toolName = pencil;
        setTool();
        DaYiConnectRoomActivity.whiteBoradBean.initValue();

        switch (pencil) {
            case Appliance.PENCIL:
                DaYiConnectRoomActivity.whiteBoradBean.setPen(true);

                break;

            case Appliance.ERASER:
                DaYiConnectRoomActivity.whiteBoradBean.setEraser(true);

                break;

            case Appliance.RECTANGLE:
                DaYiConnectRoomActivity.whiteBoradBean.setRectangular(true);

                break;
            case Appliance.SELECTOR:
                //移动工具不做处理

                break;

            case Appliance.ELLIPSE:

                DaYiConnectRoomActivity.whiteBoradBean.setCirle(true);

                break;


        }


    }

    public interface WhiteBoardFragmentListener {

        void uploadImgSuccess();

        void uploadPPTImgSuccess(CourseUploadBean courseUploadBean);
    }


    private WhiteBoardFragmentListener listener;

    public void setWhiteBoardFragmentListener(WhiteBoardFragmentListener whiteBoardFragmentListener) {

        this.listener = whiteBoardFragmentListener;

    }

    /**
     * 插入图片
     * RoomControlFragment调用
     */
    List<LocalMedia> listImage = new ArrayList<>();

    public void insertImage() {

        PhotoUtil.normalSelectPictureByCode(getActivity(), listImage, 1, PhotoUtil.WHITE_BORAD_IMAGE);

    }

    /**
     * 插入PPT
     * RoomControlFragment调用
     */
    List<LocalMedia> pptImage = new ArrayList<>();

    public void insertPPTImage() {

        PhotoUtil.normalSelectPictureByCode(getActivity(), pptImage, 1, PhotoUtil.WhiteBroadPPt_Image);

    }


    /**
     * 上传ppt和图片操作
     * MainRoomActivity调用
     * type String类型，区别图片和ppt
     * <p>
     * Bitmap用于判断图片宽高以及比例
     * course_id用于上传PPT课件
     * compressPath用于上传本地文件到七牛
     * pageIndex当前白板索引，用于获取当前白板场景，判断上传图片的显示大小
     *
     * @param compressPath
     */
    public void upLoadImage(final Bitmap bitmap, final String course_id,
                            final String type, String compressPath, final int pageIndex) {

        if (null == lin_insert) {
            LogUtil.e("========>" + lin_insert);
        } else {
            lin_insert.setVisibility(View.VISIBLE);
        }

        QiNiuUploadTask qiNiuUploadTask = new QiNiuUploadTask(getActivity());
        qiNiuUploadTask.setFileUploadListener(new FileUploadListener() {
            @Override
            public void onProgress(int progress) {

                if (null == lin_insert) {
                    LogUtil.e("========>当前进度tv_progress：" + progress);
                } else {
                    tv_progress.setText(progress + "%");
                }

            }

            @Override
            public void onSuccess(String s) {

                if ("".equals(s) || null == s || "null".equals(s) || s.length() < 5) {

                    showToast("上传失败，请重新选择!");

                } else {

                    if (null != lin_insert) {
                        lin_insert.setVisibility(View.GONE);
                    }

                    String urlHead = SharedPreferenceManager.getInstance(getContext()).getUserCache().getQiNiuUrl();

                    LogUtil.e("获取的路径：" + urlHead + s);

                    if ("image".equals(type)) {

                        if (bitmap != null) {
                            Double width = Double.valueOf(bitmap.getWidth());
                            Double height = Double.valueOf(bitmap.getHeight());

                            LogUtil.e("获取到图片的宽为：" + width + "，高为：" + height);
                            LogUtil.e("图片的宽高比例为：" + width / height);

                            //为与IOS设置相同的高度方便显示，先获取PPT的高度再进行处理
                            Double disHeight = Double.valueOf(DisplayUtil.getScreenHeight(getActivity()));
                            if (room != null) {
                                if (room.getScenes().length > 0 && pageIndex < room.getScenes().length) {
                                    Scene scene = room.getScenes()[pageIndex];
                                    if (null != scene.getPpt()) {
                                        disHeight = scene.getPpt().getHeight();
                                    }
                                }
                            }
                            LogUtil.e("获取到老师屏幕高度为：" + disHeight);
                            Double roomImgHeight = disHeight - 200d;
                            //根据比例-----图片W/H == W/H显示时
                            Double imgWidth = width * roomImgHeight / height;
                            LogUtil.e("计算出图片显示宽度为：" + imgWidth);
                            room.insertImage(new ImageInformationWithUrl(0d, 0d, imgWidth, roomImgHeight, urlHead + s));
                        }

                        if (listener != null) {
                            listener.uploadImgSuccess();
                        }
                    } else if ("pptimage".equals(type)) {

                        //上传该Ppt信息到后台
                        addPrepareImg(s, course_id);
                    }

                }
            }

            @Override
            public void onError(String e) {

                if (null != lin_insert) {
                    lin_insert.setVisibility(View.GONE);
                }

                showToast("图片上传失败");
            }
        });
        qiNiuUploadTask.execute(compressPath, SharedPreferenceManager.getInstance(getActivity()).getUserCache().getQiNiuToken());

    }

    public void addPrepareImg(String uploadUrl, String course_id) {
        HttpUtils.with(getActivity())
                .addParam("requestType", "OTO_COURS_COURSEWARE_UPLOAD")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .addParam("course_id", course_id)
                .addParam("courseware_hash", uploadUrl)
                .execute(new HttpNormalCallBack<CourseUploadBean>() {
                    @Override
                    public void onSuccess(CourseUploadBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {

                            if (listener != null) {
                                listener.uploadPPTImgSuccess(result);
                            }

                            showToast(result.getMsg());
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }


    //------------------------------------------------------------------------------------API

    private String toolName = Appliance.PENCIL;

    public void setTool() {

        Room room = DaYiConnectRoomActivity.getwhiteBoardRoom();
        MemberState memberState = new MemberState();
        // 线条的颜色，将 RGB 写在一个数组中   如果使用画笔，设置画笔颜色
        if ("1".equals(identity)) {
            int[] colorArr = {220, 20, 60};
            memberState.setStrokeColor(colorArr);
        } else if ("2".equals(identity)) {
            int[] colorArr = {0, 0, 0};
            memberState.setStrokeColor(colorArr);
        }
        memberState.setCurrentApplianceName(toolName);

        // 线条的粗细 // 文字的字号
//        memberState.setStrokeWidth(toolStrokeWidth);
//        memberState.setTextSize(toolTextSize);
        memberState.setStrokeWidth(2d);

        if (room != null) {
            room.setMemberState(memberState);
        }

        showLog("设置铅笔");

    }
}
